<?php
/**
 * Passport.php
 * User: tommy
 */

namespace app\admin\controller;

use Exception;
use lib\password\PasswordLib;
use model\admin\Admin;
use service\admin\AdminService;
use stdClass;
use Svick\Core\App;
use Svick\Core\Request;


class Passport
{
    /**
     * 管理员登录
     *
     * @return stdClass
     * @throws Exception
     */
    public function login()
    {
        $username = Request::jsonString('username');
        $password = Request::jsonString('password');

        if (empty($username) || empty($password)) {
            return App::result(1, '账号或者密码都不能为空');
        }

        //管理员
        $admin = Admin::where(['username' => $username, 'status' => 1])->row('id, type, name, username, password');
        if ($admin->isEmpty()) {
            return App::result(1, '用户不存在或已禁用');
        }
        if (PasswordLib::gen($password) != $admin->password) {
            return App::result(1, '用户名密码错误');
        }
        unset($admin->password);

        //token
        list($token, $expire) = AdminService::login($admin->id, $admin->type);

        return App::result(0, 'ok', [
            'admin' => $admin,
            'token' => $token,
            'expire' => $expire
        ]);
    }
}
